<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2022/3/16
 */

namespace App\Http\Controllers;

use App\Http\Requests\GuestbookRequest;
use App\Models\Guestbook;
use App\Services\AdsService;
use App\Services\ConfigService;
use App\Services\GuestbookService;
use App\Services\MetaService;

/**
 * 留言板咨询
 * Class GuestbookController
 * @package App\Http\Controllers
 */
class GuestbookController extends Controller
{
    private $config;

    function __construct()
    {
        // 功能是否关闭
        $this->config = $getGuestbookConfig = ConfigService::getGuestbookConfig();
        if (!$getGuestbookConfig['status']) {
            abort(404, __('guestbook.closed'));
        }
    }

    /**
     * 首页
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    function index()
    {
        //
        $data = [];
        $data['meta'] = GuestbookService::meta();
        $data['ads'] = AdsService::getAdsBySpaceIdName('guestbook');// 广告位
        $data['breadcrumb'] = GuestbookService::getBreadcrumb();
        return $this->view('guestbook/index', $data);
    }

    /**
     * 提交留言
     * @param GuestbookRequest $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    function store(GuestbookRequest $request)
    {
        // 数据校验、提交
        $data = $request->validate('store');
        unset($data['vcode']);
        // 留言次数校验
        if ($this->config['day_times'] > 0 && GuestbookService::getGuestbookTimes($data['customer_phone_number']) >= $this->config['day_times']) {
            return redirect()->route('guestbook.index')->withInput()->with(['status' => 0, 'message' => __('guestbook.error_exists')]);
        }
        $guestbook = new Guestbook($data);
        if (!$guestbook->save()) {
            return redirect()->route('guestbook.index')->withInput()->with(['status' => 0, 'message' => __('guestbook.error_submit')]);
        }
        GuestbookService::addGuestbookTimesRecord($data['customer_phone_number']);
        return redirect()->route('guestbook.index')->with(['status' => 1, 'message' => __('guestbook.success_submit')]);
    }


}
